import { plainToInstance } from "class-transformer";
import TestPaperDao from "../dao/TestPaperDao";
import TestPaperEntity from "../entities/TestPaperEntity";
import ResultHelper from "../utils/ResultHelper";
import QuestionDao from "../dao/QuestionDao";


export default class TestPaperService {

  static async create(paper: Object) {
    const Paper = plainToInstance(TestPaperEntity, paper)

    !Paper.desc ? Paper.desc = '' : Paper.desc

    const errs = await Paper.validateThie()

    if (errs.length > 0) {
      return ResultHelper.error(errs)
    }

    const result = await TestPaperDao.create(Paper)

    return ResultHelper.success(result, "添加成功")

  }

  static async findByPage(page: number = 1, limit: number = 10) {

    const offset = (page - 1) * limit

    const result = await TestPaperDao.findByPage(offset, limit)

    return ResultHelper.success(result)
  }

  static async delete(id: string = '') {
    const result = await TestPaperDao.delete(id)
    if (result) {
      // 删除 成功
      return ResultHelper.success({}, "删除成功")
    } else {
      return ResultHelper.error("删除失败")
    }
  }

  static async findById(id: string) {
    if (!id) {
      return ResultHelper.error('请携带试卷标识')
    }

    const result = await TestPaperDao.findById(id)
    const questions = result.questions
    if (questions) {
      const questionIdList = JSON.parse(questions)
      const pArr = []
      for (let i = 0; i < questionIdList.length; i++) {
        const id = questionIdList[i];
        const re = QuestionDao.findById(id)
        pArr.push(re)
      }

      const questionsList = await Promise.all(pArr)
      result.questions = questionsList
    }


    return ResultHelper.success(result)
  }

}